package com.yuan.pic;

import sun.misc.BASE64Decoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * Created by 袁恩光 on 2018/3/29.
 */
@WebServlet(urlPatterns = "/upload*", loadOnStartup = 1)
public class UploadServlet extends HttpServlet {

    private static final String USER_NAME = "username";
    private static final String PASSWORD = "password";
    private static final String PATH = "path";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Map<String, String> map = Utils.getParams();
        boolean flag = false;
        if (map.size() == 0) {
            flag = true;
        }
        if (validatePwd(req, map.get(USER_NAME), map.get(PASSWORD))) {
            flag = true;
        }

        if (!flag) {
            PrintWriter out = resp.getWriter();
            out.print("username or password error");
            return;
        }
        String msg = "success";
        PrintWriter out = resp.getWriter();
        try {
            savePic(req.getParameter("image"), req.getParameter("name"), map.get(PATH));
        } catch (Exception e) {
            e.printStackTrace();
            msg = e.getMessage();
            out.print(msg);
        }
        out.print(msg);
    }


    private boolean validatePwd(HttpServletRequest req, String userName, String password) {
        if (null == userName || "".equals(userName)) {
            return true;
        }
        //已经配置用户名
        if (userName.equals(req.getParameter(USER_NAME))) {
            //无密码访问
            if (null == password || "".equals(password)) {
                return true;
            }
            if (password.equals(req.getParameter(PASSWORD))) {
                return true;
            }
        }
        return false;
    }


    /**
     * 图片存储
     *
     * @param image    base64编码格式的文件
     * @param fileName name
     */
    private void savePic(String image, String fileName, String path) {
        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream os = null;
        try {
            byte[] b = decoder.decodeBuffer(image);
            if (null == path) {
                path = "../tmp";
            }
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            os.write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
